/**
 * 微信小程序Socket通信简单Demo
 */

var util = require('../utils/util.js')

var app = getApp();
var socketOpen = false;
var socketMsgQueue = [];
var that;

Page({
  data: {
    userInfo: {},
    socktBtnTitle: '连接socket'
  },
  onLoad: function() {
    that = this;
  },
  // 开启/断开 Socket连接
  socketBtnTap: function() {
    var remindTitle = socketOpen ? '正在关闭' : '正在连接'

    wx.showToast({
      title: remindTitle,
      icon: 'loading',
      duration: 10000
    })

    if (!socketOpen) {

      wx.connectSocket({
        url: 'ws://192.168.3.34:3000' // 启动本地Node服务，修改为本地IP地址
      })

      wx.onSocketError(function(res) {
        socketOpen = false
        console.log('WebSocket连接打开失败，请检查！')
        that.setData({
          socktBtnTitle: '连接socket'
        })
        wx.hideToast()
      })

      // Socket连接~打开
      wx.onSocketOpen(function(res) {
        console.log('WebSocket连接已打开！')
        wx.hideToast()
        that.setData({
          socktBtnTitle: '断开socket'
        })
        socketOpen = true
        for (var i = 0; i < socketMsgQueue.length; i++) {
          that.sendSocketMessage(socketMsgQueue[i])
        }
        socketMsgQueue = []
      })

      // 收到服务器内容
      wx.onSocketMessage(function(res) {
        console.log('收到服务器内容：' + res.data)
      })

      // Socket连接~关闭
      wx.onSocketClose(function(res) {
        socketOpen = false
        console.log('WebSocket 已关闭！')
        wx.hideToast()
        that.setData({
          socktBtnTitle: '连接socket'
        })
      })
    } else {
      wx.closeSocket(); // 关闭Socket服务
    }
  },
  // 发送消息给后台服务
  sendSocketMessage: function(msg) {
    if (socketOpen) {
      wx.sendSocketMessage({
        data: msg
      })
    } else {
      socketMsgQueue.push(msg)
    }
  },
  sendMessageBtnTap: function() {
    this.sendSocketMessage('小程序来了：' + new Date().format('yyyy-MM-dd hh:mm:ss'))
  }

})